package com.blacktry.controller;


import com.blacktry.entity.enums.OprLogConst;
import com.blacktry.entity.model.ApiResult;
import com.blacktry.service.AliOssService;
import com.blacktry.utils.ApiResultHandler;
import com.blacktry.utils.log.OperLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.security.Principal;

@Api(value = "Oss存储管理模块", tags = "Oss管理接口")
@RestController
@RequestMapping("/Oss")
public class AliOssController {

    @Autowired
    private AliOssService aliOssService;

    @OperLog(operModul = "用户管理-oss上传文件",operType = OprLogConst.ADD,operDesc = "oss上传文件功能")
    @ApiOperation("oss上传文件")
    @PostMapping("/uploadImgFile")
    public ApiResult upload(MultipartFile file){
        String uploadUrl = aliOssService.upload(file);
        return ApiResultHandler.buildApiResult(200,"成功",uploadUrl);
    }

    @OperLog(operModul = "用户管理-oss上传文件列表",operType = OprLogConst.ADD,operDesc = "oss上传文件列表功能")
    @ApiOperation("oss上传文件列表")
    @PostMapping("/uploadImgFileList/{examId}")
    public ApiResult upload(@RequestParam("pictures") MultipartFile[] fileList, @PathVariable("examId") String examId, Principal principal){
        String username = principal.getName();
        return ApiResultHandler.buildApiResult(200,"成功",this.aliOssService.uploadFiles(fileList,examId,username));
    }

    @OperLog(operModul = "用户管理-oss删除替换文件",operType = OprLogConst.DELETE,operDesc = "oss删除替换文件功能")
    @ApiOperation("oss删除替换文件")
    @PostMapping("/deleteImgFile")
    public ApiResult deleteImgFile(String file){
        try {
            // 去除携带http
            String[] results = file.split(".com/");
            aliOssService.deleteFile(results[1]);
            return ApiResultHandler.buildApiResult(200,"成功",null);
        }catch (Exception e){
            // 缺少错误日志输出
            return ApiResultHandler.buildApiResult(-1,"删除替换文件失败",null);
        }
    }
}
